package com.train.gateway.filter;

import com.train.gateway.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class LoginMemberFilter implements GlobalFilter {
    private final static Logger LOG = LoggerFactory.getLogger(LoginMemberFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径，判断是不是白名单里面的路径
        String path = request.getURI().getPath();
        if (path.contains("/member/login")||path.contains("/member/send-code")){
            return chain.filter(exchange);
        }

        //获取请求头里面的token进行校验
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.hasText(token)){
            System.out.println("token为空请求被拦截");
            LOG.info("token为空请求被拦截");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        if (JwtUtil.validate(token)){
            return chain.filter(exchange);
        }else {
            System.out.println("token校验失败");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }
}
